package com.grmasa.soundtoggle;

import android.content.Context;
import android.content.SharedPreferences;

public class MySharedPreference {
    private static MySharedPreference instance;
    private SharedPreferences sharedPreferences;
    private static final String DEFAULT_SP_NAME = "mySP"; // 默认的 SharedPreferences 名称

    public MySharedPreference(Context context) {
        this(context, DEFAULT_SP_NAME);
    }

    public MySharedPreference(Context context, String spName) {
        sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }

    // 获取单例实例，使用默认的 SharedPreferences 名称
    public static synchronized MySharedPreference getInstance(Context context) {
        if (instance == null) {
            instance = new MySharedPreference(context);
        }
        return instance;
    }

    // 获取单例实例，支持自定义 SharedPreferences 名称
    public static synchronized MySharedPreference getInstance(Context context, String spName) {
        if (instance == null) {
            instance = new MySharedPreference(context, spName);
        }
        return instance;
    }

    // 保存 String 类型数据
    public void put(String key, String value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.apply(); // 使用 apply() 代替 commit()，异步保存
    }

    // 读取 String 类型数据，支持默认值
    public String get(String key, String defaultValue) {
        return sharedPreferences.getString(key, defaultValue);
    }

    // 保存 int 类型数据
    public void putInt(String key, int value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    // 读取 int 类型数据，支持默认值
    public int getInt(String key, int defaultValue) {
        return sharedPreferences.getInt(key, defaultValue);
    }

    // 保存 boolean 类型数据
    public void putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    // 读取 boolean 类型数据，支持默认值
    public boolean getBoolean(String key, boolean defaultValue) {
        return sharedPreferences.getBoolean(key, defaultValue);
    }

    // 保存 float 类型数据
    public void putFloat(String key, float value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putFloat(key, value);
        editor.apply();
    }

    // 读取 float 类型数据，支持默认值
    public float getFloat(String key, float defaultValue) {
        return sharedPreferences.getFloat(key, defaultValue);
    }

    // 移除指定 key 的数据
    public void remove(String key) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        editor.apply();
    }

    // 清除所有数据
    public void clear() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}